﻿Public Class frmLoader
    Public sCurrentBroker As String
    Dim sFindField As String
    Friend WithEvents niStatus As New System.Windows.Forms.NotifyIcon

#Region "Properties"

    Private _ListOfTrades As Generic.List(Of Trade)
    Public Property ListOfTrades() As Generic.List(Of Trade)
        Get
            Return _ListOfTrades
        End Get
        Set(ByVal value As Generic.List(Of Trade))
            _ListOfTrades = value
        End Set
    End Property

    Private _CurrentBroker As Broker
    Public Property CurrentBroker() As Broker
        Get
            Return _CurrentBroker
        End Get
        Set(ByVal value As Broker)
            _CurrentBroker = value
        End Set
    End Property

    Private _LoaderError As ErrorHandler
    Public Property LoaderError() As ErrorHandler
        Get
            Return _LoaderError
        End Get
        Set(ByVal value As ErrorHandler)
            _LoaderError = value
        End Set
    End Property

    Private _fhReader As FileHandler
    Public Property fhReader() As FileHandler
        Get
            Return _fhReader
        End Get
        Set(ByVal value As FileHandler)
            _fhReader = value
        End Set
    End Property



#End Region

#Region "Button Clicks"

#Region "Broker"
    Private Sub cmdAddBroker_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddBroker.Click
        Dim brkNew As Broker = Nothing
        frmBroker.Show(brkNew)
    End Sub

    Private Sub cmdDeleteBroker_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDeleteBroker.Click
        DeleteBroker()
    End Sub

    Private Sub cmdEditSSIs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditBroker.Click
        If Not My.Settings.AllBrokers.Count = 0 Then Me.CurrentBroker = Me.lbBrokers.SelectedItem
        frmBroker.Show(Me.CurrentBroker)
    End Sub

#End Region

#Region "Application-Level"
    Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRun.Click
        Me.tsslStatus.Text = "Running..."
        ButtonsOnOff(True)
        If My.Settings.bRunOnTimer Then
            RunMinimized()
        Else
            Me.bgwRunner.RunWorkerAsync()
        End If

    End Sub

    Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
        Me.tsslStatus.Text = "Stopped."
        If Me.bgwRunner.IsBusy Then   Me.bgwRunner.CancelAsync()
        Me.timerLoader.Stop()
        ButtonsOnOff(False)
    End Sub

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        My.Settings.Holidays(0) = Me.dgvCCYHolidays.DataSource
        My.Settings.CCYSpotDays(0) = Me.dgvCCYSpotDays.DataSource
        My.Settings.Save()
        Me.tsslStatus.Text = "Settings Saved."
    End Sub

    Private Sub cmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose.Click
        Me.Close()
    End Sub
    Private Sub ButtonsOnOff(ByVal Running As Boolean)
        If Running Then
            Me.cmdRun.Enabled = False
            Me.cmdStop.Enabled = True
            Me.cmdSave.Enabled = False
            Me.cmdClose.Enabled = False
        Else
            Me.cmdRun.Enabled = True
            Me.cmdStop.Enabled = False
            Me.cmdSave.Enabled = True
            Me.cmdClose.Enabled = True
        End If
    End Sub
#End Region

#Region "Fund Mappings"

    Private Sub cmdAddFund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAddFund.Click
        Dim sFundToMap As String = InputBox("Please enter a fund code to map/rename.", "Fund Mapping", "FUNDCODE")

        If Not sFundToMap Is Nothing OrElse Not sFundToMap = String.Empty Then
            frmFundMap.Show(sFundToMap)
        End If

    End Sub

    Private Sub cmdEditFund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditFund.Click
        Try
            If Me.lbFundRouting.SelectedItem Is Nothing Then
                Logger.MsgLog("No Fund Selected for Edit.")
            Else
                Dim myFund As Fund = Me.lbFundRouting.SelectedItem
                frmFundMap.Show(myFund.FundName)
            End If


        Catch ex As Exception
            Me.LoaderError.ShowMsgbox(ex, "Fund Form Load")
        End Try
    End Sub

    Private Sub cmdDeleteFund_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDeleteFund.Click
        Dim myFund As Fund = Me.lbFundRouting.SelectedItem
        My.Settings.AllFunds.Remove(myFund)
        Me.RefreshFunds()
        My.Settings.Save()
    End Sub

#End Region

#Region "General"
    Private Sub cmdCertPathBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCertPathBrowse.Click
        If Me.ofdLoader.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.txtDigitalCertPath.Text = Me.ofdLoader.FileName
        End If
    End Sub
    Private Sub cmdInputDir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdInputDir.Click
        Me.fbdLoader.SelectedPath = Strings.Left(Me.txtInputDir.Text, Strings.InStrRev(Me.txtInputDir.Text, "\"))
        If Me.fbdLoader.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.txtInputDir.Text = Me.fbdLoader.SelectedPath
        End If
    End Sub
    Private Sub chkLTS_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkLTS.CheckedChanged
        LTSToInternetSwitch()
    End Sub
    Private Sub chkUploadOnly_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkUploadOnly.CheckedChanged
        Me.cboFileUploadType.Enabled = Me.chkUploadOnly.Checked
        If Me.chkUploadOnly.Checked Then
            Me.cboFileInputType.Enabled = False
            Me.cmdInputFileEdit.Enabled = False
        Else
            Me.cboFileInputType.Enabled = True
            Me.cmdInputFileEdit.Enabled = True
        End If

    End Sub
    Private Sub cmdInputFileEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdInputFileEdit.Click
        'TODO - Edit CRD and custom file options
        Select Case Me.cboFileInputType.SelectedItem.ToString.ToLower
            Case "crd"
                frmCRDConfig.Show()
            Case "custom file"
                frmFileConfig.Show(False)
            Case "fxc finish file", "fxc v6 csv", "swift file"
                frmFileConfig.Show(True)
            Case "fxc v6 xml", "settlement center xml", "currenex xml"
                frmFileConfig.Show(True, True)
            Case Else
                Exit Sub
        End Select
    End Sub

    Private Sub cboFileInputType_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboFileInputType.SelectedValueChanged
        If Me.cboFileInputType.SelectedItem IsNot Nothing Then
            My.Settings.sInputFileType = Me.cboFileInputType.SelectedItem
        End If
    End Sub

    Private Sub cboFileUploadType_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboFileUploadType.SelectedValueChanged
        If Me.cboFileUploadType.SelectedItem IsNot Nothing Then
            My.Settings.sFileUploadType = Me.cboFileUploadType.SelectedItem
        End If
    End Sub
    Private Sub cmdEditSQLSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEditSQLSettings.Click
        frmSQL.Show()
    End Sub
#End Region

#Region "Data Modifications"
    Private Sub cboSpotFwdOptions_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSpotFwdOptions.SelectedIndexChanged
        If Me.cboSpotFwdOptions.SelectedItem.ToString.ToLower = "specify spot days" Then
            Me.lblSpotDays.Visible = True
            Me.nudSpotDays.Visible = True
        End If
        My.Settings.sSpotFwdOption = Me.cboSpotFwdOptions.SelectedItem
    End Sub
    Private Sub chkAllNets_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAllNets.CheckedChanged
        If Me.chkAllNets.Checked = True Then
            Dim mbrResult As MsgBoxResult = MsgBox("This will net ALL trades regardless of other logic.  Are you sure you want to do this?", MsgBoxStyle.YesNo, "Warning")
            If mbrResult = MsgBoxResult.Yes Then
                Me.chkAllNets.Checked = True
            Else
                Me.chkAllNets.Checked = False
            End If
        End If
    End Sub

    Private Sub chkSellSidePerspective_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkSellSidePerspective.CheckedChanged
        If Me.chkAllNets.Checked = True Then
            Dim mbrResult As MsgBoxResult = MsgBox("This will run this program from the perspective of a sell-side institution.  Are you sure you want to do this?", MsgBoxStyle.YesNo, "Warning")
            If mbrResult = MsgBoxResult.Yes Then
                Me.chkSellSidePerspective.Checked = True
            Else
                Me.chkSellSidePerspective.Checked = False
            End If
        End If
    End Sub
#End Region

#Region "Download"
    Private Sub cmdDownloadDirBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDownloadDirBrowse.Click
        Me.fbdLoader.SelectedPath = Strings.Left(Me.txtGTSSDownloadDir.Text, Strings.InStrRev(Me.txtGTSSDownloadDir.Text, "\"))
        If Me.fbdLoader.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.txtGTSSDownloadDir.Text = Me.fbdLoader.SelectedPath
        End If
    End Sub

    Private Sub cboOutputType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboOutputType.SelectedIndexChanged
        My.Settings.sGTSSDLOutputType = Me.cboOutputType.SelectedItem
        If Me.cboOutputType.SelectedItem.ToString.ToLower = "new file" Then
            Me.txtFileNamePrefix.Enabled = False
        End If
    End Sub

    Private Sub cboFileExt_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFileExt.SelectedIndexChanged
        My.Settings.sGTSSDLFileExt = Me.cboFileExt.SelectedItem
    End Sub

    Private Sub cboDelim_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboDelim.SelectedIndexChanged
        My.Settings.sGTSSDLDelim = Me.cboDelim.SelectedItem
    End Sub

    Private Sub cmbStatusFilter_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboStatusFilter.SelectedIndexChanged
        My.Settings.sGTSSDLStatusFilter = Me.cboStatusFilter.SelectedItem
    End Sub

    Private Sub cmbDateFilter_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboDateFilter.SelectedIndexChanged
        My.Settings.sGTSSDLDateFilter = Me.cboDateFilter.SelectedItem
    End Sub

    Private Sub chkDLTime_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkDLTime.CheckedChanged
        If Me.chkDLTime.Checked Then
            Me.nudDaysPrior.Enabled = False
            Me.nudDaysAfter.Enabled = False
        End If
    End Sub

#End Region

#Region "Download Fields"

    Private Sub cmdSelect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSelect.Click
        Dim drSelected As dsDLFields.DLFieldsRow = lbFields.SelectedItem
        If drSelected Is Nothing Then Exit Sub

        drSelected.Selected = True
        drSelected.Index = Me.lbSelectedFields.Items.Count
        My.Settings.DLFields.PopulateListBoxes()

    End Sub

    Private Sub cmdUnselect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUnselect.Click
        Dim drSelected As dsDLFields.DLFieldsRow = lbSelectedFields.SelectedItem
        If drSelected Is Nothing Then Exit Sub

        drSelected.Selected = False
        drSelected.Index = -1
        My.Settings.DLFields.PopulateListBoxes()

    End Sub

    Private Sub cmdMoveUp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMoveUp.Click
        Dim drSelected As dsDLFields.DLFieldsRow = Me.lbSelectedFields.SelectedItem
        If drSelected Is Nothing OrElse drSelected.Index = 0 Then Exit Sub

        Dim iSelected As Integer = Me.lbSelectedFields.SelectedIndex - 1
        Dim drAbove As dsDLFields.DLFieldsRow = Me.lbSelectedFields.Items(iSelected)

        drSelected.Index = drSelected.Index - 1
        drAbove.Index = drAbove.Index + 1
        My.Settings.DLFields.PopulateListBoxes()

    End Sub

    Private Sub cmdMoveDown_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdMoveDown.Click
        Dim drSelected As dsDLFields.DLFieldsRow = Me.lbSelectedFields.SelectedItem
        If drSelected Is Nothing OrElse drSelected.Index = 0 Then Exit Sub

        Dim iSelected As Integer = Me.lbSelectedFields.SelectedIndex + 1
        Dim drBelow As dsDLFields.DLFieldsRow = Me.lbSelectedFields.Items(iSelected)

        drSelected.Index = drSelected.Index + 1
        drBelow.Index = drBelow.Index - 1
        My.Settings.DLFields.PopulateListBoxes()

    End Sub
#End Region

#End Region

#Region "Private Methods"

    Private Sub frmLoader_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If My.Settings.bRunOnTimer Then niStatus.Visible = False

    End Sub

    Private Sub frmLoader_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.LoaderError = New ErrorHandler

        Try
            Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
            Me.cmdStop.Enabled = False
            Me.ListOfTrades = New Generic.List(Of Trade)
            If My.Settings.AllBrokers Is Nothing Then My.Settings.AllBrokers = New BrokerList
            If My.Settings.AllFunds Is Nothing Then My.Settings.AllFunds = New FundList
            RefreshBrokers()
            RefreshFunds()
            LTSToInternetSwitch()
            If My.Settings.bFileUploadOnly Then
                Me.cboFileInputType.Enabled = False
                Me.cmdInputFileEdit.Enabled = False
            End If
            'ddls on General tab
            Me.cboFileInputType.SelectedItem = My.Settings.sInputFileType
            Me.cboFileUploadType.SelectedItem = My.Settings.sFileUploadType
            'ddls on Data Mod tab
            Me.cboSpotFwdOptions.SelectedItem = My.Settings.sSpotFwdOption
            'ddl on GTSS Download tab
            Me.cboOutputType.SelectedItem = My.Settings.sGTSSDLOutputType
            Me.cboFileExt.SelectedItem = My.Settings.sGTSSDLFileExt
            Me.cboDelim.SelectedItem = My.Settings.sGTSSDLDelim
            Me.cboStatusFilter.SelectedItem = My.Settings.sGTSSDLStatusFilter
            Me.cboDateFilter.SelectedItem = My.Settings.sGTSSDLDateFilter
            InitDatatables()
            If My.Settings.bRunOnTimer Then
                RunMinimized()
            Else
                If My.Settings.bRunOnLoad Then bgwRunner.RunWorkerAsync()
            End If

        Catch ex As Exception
            Me.LoaderError.ShowMsgbox(ex, "Settings Load")
        End Try
    End Sub

    Private Sub bgwRunner_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles bgwRunner.Disposed
        Me.ButtonsOnOff(False)
    End Sub
    Private Sub RunMinimized()
        niStatus.Icon = New System.Drawing.Icon(My.Application.Info.DirectoryPath & "\fximage.ico")
        niStatus.Visible = True
        ShowTip("Translator running.  Double-click here to restore.")
        Me.WindowState = FormWindowState.Minimized
        Me.ShowInTaskbar = False
        Me.timerLoader.Interval = My.Settings.iTimer * 10000
        Me.timerLoader.Start()
    End Sub

    Private Sub niStatus_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles niStatus.DoubleClick
        Me.ShowInTaskbar = True
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub bgwRunner_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwRunner.DoWork
        Me.fhReader = New FileHandler
        Me.ListOfTrades = Me.fhReader.ReadInFiles()
        Dim dmDataMod As New DataModifier
        dmDataMod.ModifyTrades(Me.ListOfTrades)
        Dim opSendTrades As New Output
        opSendTrades.CreateMT300(Me.ListOfTrades)
        opSendTrades.UploadToGTSS()
        opSendTrades.Archive()
        If My.Settings.bGTSSDownload Then
            Dim dlGTSSTrades As New Downloader
            dlGTSSTrades.DownloadTrades()
        End If


    End Sub
    Private Sub bgwRunner_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgwRunner.RunWorkerCompleted
        Me.ButtonsOnOff(False)
        Me.tsslStatus.Text = "Run Completed."
        If My.Settings.bRunOnLoad Then
            Me.timerLag.Start() ' gives 2.5 seconds before closing after the background worker is done running.
        End If
    End Sub

    Private Sub timerLag_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLag.Tick
        Me.Close()
    End Sub
    Private Sub timerLoader_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerLoader.Tick
        ButtonsOnOff(True)
        Me.bgwRunner.RunWorkerAsync()
    End Sub
    Private Sub InitDatatables()
        'initialize Datatable Settings
        If My.Settings.NDFDetails Is Nothing Then
            My.Settings.NDFDetails = New NDFDetails
            My.Settings.NDFDetails.Add(New dsFund.NDFDeetsDataTable)
        End If
        If My.Settings.Holidays Is Nothing Then
            My.Settings.Holidays = New Holidays
            My.Settings.Holidays.Add(New dsHolidays.HolidaysDataTable)
        End If
        If My.Settings.CCYSpotDays Is Nothing Then
            My.Settings.CCYSpotDays = New CCYSpotDays
            My.Settings.CCYSpotDays.Add(New dsCCYSpotDays.CCYSpotDaysDataTable)
        End If
        If My.Settings.DLFields Is Nothing Then
            My.Settings.DLFields = New DLFields
            My.Settings.DLFields.Add(New dsDLFields.DLFieldsDataTable)
            My.Settings.DLFields.Init()
        End If
        If My.Settings.CCYMap Is Nothing Then
            My.Settings.CCYMap = New CCYMap
            My.Settings.CCYMap.Add(New dsCCYMap.CCYMapDataTable)
        End If

        Me.dgvCCYHolidays.DataSource = My.Settings.Holidays(0)
        Me.dgvCCYSpotDays.DataSource = My.Settings.CCYSpotDays(0)
        Me.dgvCCYMapping.DataSource = My.Settings.CCYMap(0)
        My.Settings.DLFields.PopulateListBoxes()
        Me.dgvCCYHolidays.Columns(0).Visible = False
        Me.dgvCCYSpotDays.Columns(0).Visible = False
        Me.dgvCCYMapping.Columns(0).Visible = False

    End Sub

    Private Sub RefreshBrokers()
        Me.lbBrokers.Items.Clear()
        For Each brk As Broker In My.Settings.AllBrokers
            Me.lbBrokers.Items.Add(brk)
        Next
    End Sub
    Private Sub RefreshFunds()
        Me.lbFundRouting.Items.Clear()
        For Each f As Fund In My.Settings.AllFunds
            Me.lbFundRouting.Items.Add(f)
        Next
    End Sub
    Private Sub DeleteBroker()
        Dim brkDelete As Broker = Me.lbBrokers.SelectedItem
        My.Settings.AllBrokers.RemoveAt(brkDelete.ID - 1)
        RefreshBrokers()
    End Sub
    Private Sub LTSToInternetSwitch()
        If Me.chkLTS.Checked Then
            Me.txtServerIP.Enabled = True
            Me.txtInternetProxy.Enabled = True
            Me.txtProxyPort.Enabled = True
            Me.txtDigitalCertPath.Enabled = False
            Me.txtDigitalCertPW.Enabled = False
            Me.cmdCertPathBrowse.Enabled = False
        Else
            Me.txtServerIP.Enabled = False
            Me.txtInternetProxy.Enabled = False
            Me.txtProxyPort.Enabled = False
            Me.txtDigitalCertPath.Enabled = True
            Me.txtDigitalCertPW.Enabled = True
            Me.cmdCertPathBrowse.Enabled = True
        End If
    End Sub

    Private Sub ShowTip(ByVal Message As String)
        niStatus.BalloonTipIcon = ToolTipIcon.Info
        niStatus.BalloonTipText = Message
        niStatus.BalloonTipTitle = "GTSS Loader"
        niStatus.ShowBalloonTip(2000)
    End Sub

    Private Sub chkRunOnLoad_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkRunOnLoad.CheckedChanged
        If chkRunOnLoad.Checked = False Then Me.timerLag.Stop()
    End Sub

    Private Sub chkRunTimer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkRunTimer.CheckedChanged
        If Me.chkRunTimer.Checked = False Then Me.timerLoader.Stop()
    End Sub
#End Region




End Class


